<?php

namespace App\Http\Controllers\Adminer;

use App\Exceptions\BaseException;
use App\Http\Controllers\AdminController;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class PublicController extends AdminController
{
    public function login(){
        if(Auth::check()){
            return redirect("/manage");
        }
        $data['title'] = "登录";
        return view("adminer.public.login",$data);
    }
    /**
     * 处理身份认证尝试.
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        if(Auth::check()){
            return $this->successResponse('已经登录',[],200,'/manage');
        }
        $user=$request->only(['username','password']);
        // 验证不为空
        Validator::make($user, [
            'username' => [
                'bail',
                'required',
            ],
            'password' => [
                'bail',
                'required',
            ],
        ],[
            'username.required'       => '请输入用户名',
            'password.required'         => '请输入密码',
        ])->validate();
        if (Auth::attempt($user)) {
            $admin = Admin::find(auth()->user()->id);
            Auth::login($admin);
            // 认证通过后，修改用户表登录次数等字段，写入系统日志
            $admin->lasttime = date('Y-m-d H:i:s');
            $admin->lastip = $request->getClientIp();
            $admin->logincount = $admin->logincount+1;
            $admin->save();
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"登录成功");
            return $this->successResponse('登录成功',[],200,'/manage');
        }else{
            // 写入系统日志
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"尝试登录 ".$user['username']." 密码错误","-1");
            throw new BaseException('账户或密码错误');
        }
    }

    /**
     * 退出
     */
    public function logout(){
        // 写入日志
        AdminLogController::writeLog($_SERVER["QUERY_STRING"],'',"退出登录");
        Auth::logout();
        return redirect('/manage');
    }

    public function reset(){
        if(!Auth::check()){
            return redirect(route('login'));
        }
        $data['title'] = "修改密码";
        $data['title_en'] = "Reset Password";
        $data['title_url'] = route("resetpass");
        $data['info'] = Admin::find(auth()->user()->id);
        $data['is_search'] = FALSE;
        return view("adminer.public.reset",$data);
    }
    /**
     * 修改用户密码提交
     * @param Request $request
     */
    public function userUpdate(Request $request){
        $user=$request->only(['password','password1','password1_confirmation']);
        // 验证不为空
        Validator::make($user, [
            'password' => ['bail','required',],
            'password1' => ['bail','required','confirmed',]
        ],[
            'password.required'       => '请输入原始密码',
            'password1.required'         => '请输入更新密码',
            'password1.confirmed'         => '两次输入的密码不一致',
        ])->validate();
        // 匹配原密码是否正确
        if(!Hash::check($user['password'],auth()->user()->password)){
            AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"原密码输入错误");
            throw new BaseException('原密码输入错误');
        }
        // 保存密码
        $admin = Admin::find(auth()->user()->id);
        $admin->password = Hash::make($user['password1']);
        $admin->save();
        AdminLogController::writeLog($_SERVER["QUERY_STRING"],json_encode($_POST),"修改密码");
        return $this->successResponse('修改成功',[],200,route('logout'));
    }
}
